/**
 * Copyright (c) 2017, 西安星沙网络科技-版权所有
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.waleychain.exchange.consumer.config;

import java.text.SimpleDateFormat;
import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

import cn.waleychain.exchange.core.utils.DateUtils;

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

	@Override
	public void addCorsMappings(CorsRegistry registry) {
		
		registry.addMapping("/api/**").allowedHeaders("Authorization", "x-requested-with", "Content-Type", "Accept").allowedOrigins("*").allowedMethods("POST", "GET", "DELETE");
	}
	
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		super.configureMessageConverters(converters);
		MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();

	    ObjectMapper objectMapper = new ObjectMapper();
	    // 序列换成json时,将所有的long变成string
	    // 因为js中得数字类型不能包含所有的java long值
	    SimpleModule simpleModule = new SimpleModule();
	    simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
	    simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
	    objectMapper.registerModule(simpleModule);
	    objectMapper.setDateFormat(new SimpleDateFormat(DateUtils.longFormat));

	    jackson2HttpMessageConverter.setObjectMapper(objectMapper);
	    converters.add(jackson2HttpMessageConverter);
		
		
		/*FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
		//2、添加fastJson 的配置信息，比如：是否要格式化返回的json数据;
		 FastJsonConfig fastJsonConfig = new FastJsonConfig();
		 fastJsonConfig.setDateFormat(DateUtils.longFormat);
		 //3、在convert中添加配置信息.
		 fastConverter.setFastJsonConfig(fastJsonConfig);
		 //4、将convert添加到converters当中.
		 converters.add(fastConverter);*/
	}
	
}
